package com.commerce.recording.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.commerce.recording.R;
import com.commerce.recording.adapter.MylistAdapter;
import com.commerce.recording.entity.Sign;
import com.commerce.recording.utils.FormatDate;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.media.MediaPlayer.SEEK_CLOSEST;

public class PlayActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private SeekBar seekBar;
    private TextView tvName;
    private Timer timer;
    private Button mPalyBtnPause;
    private ListView palyLvSign;
    private List<Sign> signs;
    private TextView tvTime;
    private MySeekBar mySeekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        initMediaPalyer();
    }

    private void initMediaPalyer() {
        findViewById(R.id.play_tv_back).setOnClickListener((v -> finish()));
        tvName = findViewById(R.id.play_tv_name);
        seekBar = findViewById(R.id.play_sb_record);
        mPalyBtnPause = findViewById(R.id.play_btn_pause);
        palyLvSign = findViewById(R.id.paly_lv_sign);
        tvTime = findViewById(R.id.play_tv_time);
        Intent intent = getIntent();
        //获取传过来的值
        signs = (List<Sign>) intent.getSerializableExtra("signs");
        String path = intent.getStringExtra("path");
        String name = intent.getStringExtra("name");
        tvName.setText(name);
        MylistAdapter mylistAdapter = new MylistAdapter(this, signs);
        palyLvSign.setAdapter(mylistAdapter);
        //播放音频
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            //同步进度条最大值
            seekBar.setMax(mediaPlayer.getDuration());
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //实时同步进度
        timer = new Timer();
        timer.scheduleAtFixedRate(new MyThread(), 0, 200);
        new MySeekBar().start();
        clickListener();
    }

    private void clickListener() {

        palyLvSign.setOnItemClickListener((parent, view, position, id) -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mediaPlayer.seekTo(signs.get((int) id).getaLong(), MediaPlayer.SEEK_PREVIOUS_SYNC );
            }else {
                mediaPlayer.seekTo((int) signs.get((int) id).getaLong());
            }
        });
      
        mPalyBtnPause.setOnClickListener((v) -> {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                mPalyBtnPause.setText("播放");
            }else{
                mediaPlayer.start();
                mPalyBtnPause.setText("暂停");
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //值改变
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){

            }
            //值改变前
            @Override
            public void onStartTrackingTouch(SeekBar seekBar){

            }
            //值改变后
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
    }



    //设置一个线程运行进度条
    class MyThread extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //判断当前播放位置是否小于总时长
                    tvTime.setText(FormatDate.tommss(mediaPlayer.getCurrentPosition())+" / "+FormatDate.tommss(mediaPlayer.getDuration()));
                }
            });
        }
    }

    class MySeekBar extends Thread{
        @Override
        public void run() {
            while (seekBar.getProgress() <= seekBar.getMax()&&mediaPlayer!=null) {
                //设置进度条当前位置为音频播放位置
                try{
                int position = mediaPlayer.getCurrentPosition();
                seekBar.setProgress(position);
                }catch (IllegalStateException ignored){

                }
            }
        }
    }

    @Override
    protected void onStop() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        super.onStop();
    }

}